package com.rupertjones.globalcron.web;

import com.rupertjones.globalcron.domain.Host;
import net.sourceforge.stripes.action.Before;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.HandlesEvent;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.Validate;
import net.sourceforge.stripes.validation.ValidateNestedProperties;
import org.springframework.security.access.prepost.PreAuthorize;

/**
 * <p>&copy Rupert Jones 2011,2012</p>
 *
 * @author rup
 */
@PreAuthorize("hasRole('ROLE_ADMIN')")
public class AddNewHostAction extends AbstractFormAction {

    public static final String ADD_HOST_JSP = "/WEB-INF/jsp/add_host.jsp";
    @ValidateNestedProperties({
        @Validate(field = "name", required = true, on = { "SaveOrUpdate" }),
        @Validate(field = "hostname", required = true, on = { "SaveOrUpdate" })
    })
    private Host host;

    @Before(stages = LifecycleStage.BindingAndValidation)
    public void loadAndBind() {
        if (host == null) {
            host = new Host();
        }
    }

    public Host getHost() {
        return host;
    }

    @DefaultHandler
    public Resolution view() {
        return new ForwardResolution(ADD_HOST_JSP);
    }

    @HandlesEvent("SaveOrUpdate")
    public Resolution onSave() {
        getJobService().save(host);
        return new ForwardResolution(INFO_HOSTS_ACTION);
    }
}
